/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.dess.message.wechat.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.hyts.dess.message.wechat.config.WechatUrlConfig;
import com.hyts.dess.message.wechat.domain.WechatConfigProperties;
import com.hyts.dess.message.wechat.domain.WechatMessageRequest;
import com.hyts.dess.message.wechat.service.WechatApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @project-name:dess
 * @package-name:com.hyts.dess.message.wechat.service.impl
 * @author:LiBo/Alex
 * @create-date:2020-08-06 10:26
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
@Service
public class WechatApiServiceImpl implements WechatApiService {


    @Autowired
    private WechatConfigProperties wechatConfigProperties;


    /**
     * 缓存访问token数据集合
     * 构造器
     */
    LoadingCache<String, String> mAccessTokenCache = CacheBuilder.newBuilder().expireAfterWrite(7200, TimeUnit.SECONDS).
            build(new CacheLoader<String, String>() {
                @Override
                public String load(String key) {
                    // key: appId#appSecret
                    String[] array = key.split(DEFAULT_SPLIT_TOKEN);
                    Preconditions.checkArgument(array.length != 2,"load access_token error, key = " + key);
                    return getAccessToken(array[0], array[1]).getString(ACCESS_TOKEN_KEY);
                }
    });

    /**
     * 获取相关的AccessToken
     * @return
     */
    @Override
    public String getAccessToken() {
        //缓存key键值操作服务处理
        String cacheKey = wechatConfigProperties.getAppId() + DEFAULT_SPLIT_TOKEN + wechatConfigProperties.getSecretKey();
        try {
            //获取缓存信息根据key值
            return mAccessTokenCache.get(cacheKey);
        } catch (ExecutionException e) {
            log.error("#getAccessToken error, cacheKey=" + cacheKey, e);
        }
        return null;
    }

    /**
     * 获取相关的AccessToken数据值
     * @param appId
     * @param secretKey
     * @return
     */
    @Override
    public JSONObject getAccessToken(String appId, String secretKey) {
        String apiUrl = StrUtil.format(WechatUrlConfig.GET_ACCESS_TOKEN.getValue(), appId, secretKey);
        String body = HttpRequest.get(apiUrl).execute().body();
        return throwErrorMessageIfExists(body);
    }

    /**
     * 模板传输
     * @param accessToken
     * @param wechatMessageRequest
     */
    @Override
    public JSONObject templateSend(String accessToken, WechatMessageRequest wechatMessageRequest) {
        String apiUrl = StrUtil.format(WechatUrlConfig.SEND_MESSAGE.getValue(), StrUtil.isEmpty(accessToken) ? getAccessToken() : accessToken);
        String body = HttpRequest.post(apiUrl).body(JSON.toJSONString(wechatMessageRequest)).execute().body();
        return throwErrorMessageIfExists(body);
    }

    /**
     * jscode编码信息控制操作
     * @param js_code
     * @return
     */
    @Override
    public JSONObject getOpenIdByJSCode(String js_code) {
        String apiUrl = StrUtil.format(WechatUrlConfig.JS_CODE.getValue(),
                wechatConfigProperties.getAppId(),wechatConfigProperties.getSecretKey(), js_code);
        String body = HttpRequest.get(apiUrl).execute().body();
        return throwErrorMessageIfExists(body);
    }

    public static void main(String[] args) {
//        String callMethodName = (new Throwable()).getStackTrace()[1].getMethodName();
//        System.out.println(callMethodName);
        System.out.println(StrUtil.format("123{}", "1231"));

    }
}
